//
//  HNFly.m
//  HeroNuts
//
//  Created by Magic on 4/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HNFly.h"
#import "HNLogicPosition.h"
#import "HNActionCache.h"
#import "math.h"
#import "HNActorInfoCache.h"
#import "CCSpriteFrameCache.h"
#import "HNAudioEngine.h"

#define PIXELPERFLY 112

@interface HNFly(assist)

-(void) runRestSequence;
-(void) turnAroundWithActor:(NSString *)actor;
-(void) toggleFaceDirection;
-(void) playSoundEffect;
-(void) logicMove;

@end

@implementation HNFly

#pragma mark HNFly - initialization - preparing the action sequence to be run

-(id) initWithActorName:(NSString *)actor from:(CGPoint)start to:(CGPoint)end faceRight:(BOOL)faceRight
{
	if ((self = [super init])) 
	{
		actions_ = [[NSMutableArray alloc] init];
		
		int deltaX = (int)(end.x - start.x);
		
		//turn around when needed
		if ((deltaX<0 && faceRight)||(deltaX>0 && !faceRight))
		{
			[self turnAroundWithActor:actor];
		}
		
		//launch
		CCAnimate *moveStart = [[HNActionCache sharedActionCache] actionByName:@"MOVE_START" actor:actor];
		[actions_ addObject:moveStart];
		
        //prepare for logic movement
        destination_ = end;
        
		//fly
		CGPoint distance = [HNLogicPosition distanceInPixelsFrom:start to:end];
		
		int times = sqrt(distance.x*distance.x+distance.y*distance.y)/PIXELPERFLY;
		
		CCAnimate *fly = [[HNActionCache sharedActionCache] actionByName:@"MOVING" actor:actor];
        CCCallFunc *playEffect = [CCCallFunc actionWithTarget:self selector:@selector(playSoundEffect)];
        CCSpawn *flyWithEffect = [CCSpawn actionOne:fly two:playEffect];
        
        CCRepeat *repeatFly = [CCRepeat actionWithAction:flyWithEffect times:times];
        CCMoveBy *move = [CCMoveBy actionWithDuration:repeatFly.duration position:distance];
		CCCallFunc *logicMove = [CCCallFunc actionWithTarget:self selector:@selector(logicMove)];
        
		CCSpawn *spawn = [CCSpawn actions:repeatFly, logicMove, move, nil];
        
		[actions_ addObject:spawn];
                
		//landing
		CCAnimate *moveEnd = [[HNActionCache sharedActionCache] actionByName:@"MOVE_END" actor:actor];
		[actions_ addObject:moveEnd];
	}
	
	return self;
}

- (void)playSoundEffect
{
    [[HNAudioEngine sharedEngine] playSoundEffectWithActor:target_.name action:@"MOVING"];
}

-(void) turnAroundWithActor:(NSString *)actor
{
    CCAnimate *turnLeft = [[HNActionCache sharedActionCache] actionByName:@"TURN_L" actor:actor];
    CCAnimate *turnRight = [[HNActionCache sharedActionCache] actionByName:@"TURN_R" actor:actor];
    CCCallFunc *toggleFace = [CCCallFunc actionWithTarget:self selector:@selector(toggleFaceDirection)];
    
    [actions_ addObject:turnLeft];
    [actions_ addObject:toggleFace];
    [actions_ addObject:turnRight];
}

-(void) toggleFaceDirection
{
    target_.faceRight = !target_.faceRight;
}

-(void) logicMove
{
    target_.position = destination_;
}

@end
